//
//  YCSelectTrainMethodViewController.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/1.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  选择训练方式

#import "YCSelectTrainMethodViewController.h"
#import "YCFillApplyInfoViewController.h"
#import "YCCarServiceViewController.h"
#import "YCTrainMethodCell.h"
#import "YCTrainMethodButton.h"
#import "YCPeriodModel.h"
#import "YCPlaceModel.h"


@interface YCSelectTrainMethodViewController ()<UITableViewDelegate,UITableViewDataSource>

/** 表  */
@property (nonatomic, strong) UITableView *tableView;
/** footerView */
@property (nonatomic, strong) UIView *footerView;
/** 底部条  */
@property (nonatomic, strong) UIView *bottomView;


/** 时段  */
@property (nonatomic, copy) NSString *trainTimeStr;
/** 场地  */
@property (nonatomic, copy) NSString *placeStr;

/** 时间数据  */
@property (nonatomic, strong) NSArray *periodArray;
/** 场地数据  */
@property (nonatomic, strong) NSArray *placeArray;
/** 填写资料的模型  */
@property (nonatomic, strong) YCFillInfomationModel *fillInfoModel;
@end

@implementation YCSelectTrainMethodViewController
- (UITableView *)tableView
{
    if(!_tableView)
    {
        CGRect rect = CGRectMake(0, 0, self.view.yc_width, self.view.yc_height - 50);
        _tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = self.footerView;
        _tableView.contentInset = UIEdgeInsetsMake(heightFromIphone6Height(146), 0, 0, 0);
    }
    return _tableView;
}
// footerView
- (UIView *)footerView
{
    if(!_footerView)
    {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 120)];
        _footerView.backgroundColor = [UIColor whiteColor];
        
//        YCTrainMethodButton *placeSearchBtn = [[YCTrainMethodButton alloc] init];
//        [placeSearchBtn setImage:[UIImage imageNamed:@"坐标"] forState:UIControlStateNormal];
//        [placeSearchBtn setImage:[UIImage imageNamed:@"坐标"] forState:UIControlStateHighlighted];
//        [placeSearchBtn setTitle:@"场地查询" forState:UIControlStateNormal];
//        [placeSearchBtn setTitle:@"场地查询" forState:UIControlStateHighlighted];
//        [placeSearchBtn addTarget:self action:@selector(didTouchUpInsidePlaceSearchButton:) forControlEvents:UIControlEventTouchUpInside];
//        [_footerView addSubview:placeSearchBtn];
        
        
        
        YCTrainMethodButton *gotoBtn = [[YCTrainMethodButton alloc] init];
        [gotoBtn setImage:[UIImage imageNamed:@"班车服务"] forState:UIControlStateNormal];
        [gotoBtn setImage:[UIImage imageNamed:@"班车服务"] forState:UIControlStateHighlighted];
        [gotoBtn setTitle:@"前往班车" forState:UIControlStateNormal];
        [gotoBtn addTarget:self action:@selector(didTouchUpInsideGotoButton:) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:gotoBtn];
        
//        [placeSearchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(_footerView).offset(45);
//            make.centerY.equalTo(_footerView);
//            make.height.equalTo(@35);
//            make.width.equalTo(@100);
//        }];
        
        [gotoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.right.equalTo(_footerView).offset(-45);
            make.centerX.equalTo(_footerView);
            make.centerY.equalTo(_footerView);
            make.height.equalTo(@35);
            make.width.equalTo(@100);
        }];
    }
    return _footerView;
}

// 底部条
- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        // 下一步
        UIButton *nextStep = [[UIButton alloc] init];
        [nextStep setTitle:@"下一步" forState:UIControlStateNormal];
        [nextStep setTitleColor:[UIColor yc_colorWithUInt:0x4766ab] forState:UIControlStateNormal];
        nextStep.titleLabel.font = [UIFont systemFontOfSize:16];
        [nextStep addTarget:self action:@selector(didTouchUpInsideNextStepButton:) forControlEvents:UIControlEventTouchUpInside];
        
        // 分隔线
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.2];
        
        [_bottomView addSubview:nextStep];
        [_bottomView addSubview:line];
        
        [nextStep mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_bottomView).offset(-33);
            make.centerY.equalTo(_bottomView);
        }];
        
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(_bottomView);
            make.height.equalTo(@1);
        }];
    }
    return _bottomView;
}

#pragma mark - 生命周期

- (id)initWithFillInfoModel:(YCFillInfomationModel *)model
{
    if (self = [super init]) {
        _fillInfoModel = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self yc_addBackBarButtonItem];
    self.navigationItem.title = @"选择训练方式";
    self.trainTimeStr = @"上午";// 默认
    self.placeStr = @"A训练场";
    _fillInfoModel.periodidName = self.trainTimeStr;
    _fillInfoModel.spaceName = self.placeStr;
    [self makeView];
    YCWeakSelf;
    self.tableView.mj_header = [YCRefreshHeader headerWithRefreshingBlock:^{
        [weakSelf loadPeriodData];
        [weakSelf loadPlaceData];
    }];
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)makeView
{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 数据处理
- (void)loadPeriodData
{
    if(!self.fillInfoModel.cartypeid)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择车型"];
        return;
    }
    if(!self.fillInfoModel.classtypeid)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择班型"];
        return;
    }
    NSDictionary *params = @{
                             @"uid":@"1",
                             @"token":accessToken_Test,
                             @"cartypeid":@(self.fillInfoModel.cartypeid),
                             @"classtypeid":@(self.fillInfoModel.classtypeid),
                             };
    [[YCNetworManager shareManager] postWithUrl:YCAPISelectPeriod params:params success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        self.periodArray = [YCPeriodModel yc_objectArrayWithKeyValuesArray:response.data];
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadPlaceData
{
    if(!self.fillInfoModel.cartypeid)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择车型"];
        return;
    }
    if(!self.fillInfoModel.classtypeid)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择班型"];
        return;
    }
    if(!self.fillInfoModel.periodid)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择时段"];
        return;
    }
    NSDictionary *params = @{
                             @"uid":@"1",
                             @"token":accessToken_Test,
                             @"cartypeid":@(self.fillInfoModel.cartypeid),
                             @"classtypeid":@(self.fillInfoModel.classtypeid),
                             @"periodidtypeid":@(self.fillInfoModel.periodid),
                             };
    [[YCNetworManager shareManager] postWithUrl:YCAPISelectPlace params:params success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        self.placeArray = [YCPlaceModel yc_objectArrayWithKeyValuesArray:response.data];
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YCTrainMethodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    if (!cell) {
        cell = [[YCTrainMethodCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"tableViewCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = [UIColor lightGrayColor];
        cell.detailTextLabel.textColor = [UIColor yc_colorWithUInt:0x808080];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:16];
    }
    if (indexPath.row == 0) {
        cell.textLabel.text = @"选择时段";
        cell.detailTextLabel.text = self.trainTimeStr;
    } else {
        cell.textLabel.text = @"选择训练场地";
        cell.detailTextLabel.text = self.placeStr;
    }
    return cell;
}

#pragma mark - UITableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return heightFromIphone6Height(48);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
        if (!self.periodArray) {
            [self loadPeriodData];
//            [SVProgressHUD showInfoWithStatus:@"加载数据中..."];
            return;
        }
        NSMutableArray *periodArray = [NSMutableArray array];
        for (NSInteger i = self.periodArray.count - 1; i>=0; i--) {
            YCPeriodModel *model = self.periodArray[i];
            [periodArray addObject:model.title];
        }
        LXActionSheet *actionSheet = [[LXActionSheet alloc] initWithCancelButtonTitle:@"取消" otherButtonTitlesArray:periodArray];
        [actionSheet showInView:self.view mask:YES click:^(NSUInteger index, LXActionSheet *sheet) {
            YCPeriodModel *model = self.periodArray[self.periodArray.count - index];
            self.fillInfoModel.periodid = model.periodid;
            self.fillInfoModel.periodidName = model.title;
            self.trainTimeStr = model.title;//periodArray[index-1];
            [tableView reloadData];
        } cancel:nil];
    } else {
        if (!self.placeArray) {
            [self loadPlaceData];
//            [SVProgressHUD showInfoWithStatus:@"加载数据中..."];
            return;
        }
        NSMutableArray *placeArray = [NSMutableArray array];
        for (NSInteger i = self.placeArray.count - 1; i>=0; i--) {
            YCPlaceModel *model = self.placeArray[i];
            [placeArray addObject:model.title];
        }
        LXActionSheet *actionSheet = [[LXActionSheet alloc] initWithCancelButtonTitle:@"取消" otherButtonTitlesArray:placeArray];
        [actionSheet showInView:self.view mask:YES click:^(NSUInteger index, LXActionSheet *sheet) {
            YCPlaceModel *model = self.placeArray[self.placeArray.count - index];
            self.fillInfoModel.spaceid = model.spaceid;
            self.fillInfoModel.spaceName = model.title;
            self.placeStr = model.title;//placeArray[index-1];
            [tableView reloadData];
        } cancel:nil];
    }
    
    
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    return self.footerView;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 120;
//}

#pragma mark - 监听点击事件
//场地查询
- (void)didTouchUpInsidePlaceSearchButton:(YCTrainMethodButton *)button
{
    YCLogFunc

}

//前往班车
- (void)didTouchUpInsideGotoButton:(YCTrainMethodButton *)button
{
    YCLogFunc
    YCCarServiceViewController *carService = [[YCCarServiceViewController alloc] init];
    [self.navigationController pushViewController:carService animated:YES];
    
}

// 下一步
- (void)didTouchUpInsideNextStepButton:(UIButton *)button
{
    YCLogFunc
    YCFillApplyInfoViewController *fillApplyInfoVC = [[YCFillApplyInfoViewController alloc] initWithFillInfoModel:self.fillInfoModel];
    [self.navigationController pushViewController:fillApplyInfoVC animated:YES];
}


@end
